/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @CommUtil.java  2014年3月25日 下午5:39:37 - Guzhu
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSON;
import com.android.tiango.baba.BaBaseApplication;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.db.Area;
import com.android.tiango.baba.db.City;
import com.android.tiango.baba.db.DbHelper;
import com.android.tiango.baba.db.Province;
import com.android.tiango.baba.entity.BaseDataEntity;
import com.nineoldandroids.util.StringUtil;

public class CommUtil {
	// public static BaseToken mBaseToken;
	/**
	 * 是否有网络
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {
			// 如果仅仅是用来判断网络连接 ,则可以使用 cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 验证邮箱地址是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			// String check =
			// "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			String check = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 检测密码
	 * 
	 * @param pwd
	 * @return
	 */
	public static boolean checkPwd(String pwd) {
		boolean flag = false;
		try {
			String check = "^[a-zA-Z0-9]{6,20}+$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(pwd);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 验证手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		boolean flag = false;
		try {
			// Pattern p = Pattern.compile("^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])\\d{8}$");
			Pattern p = Pattern.compile("^(1[3-9])\\d{9}$");
			Matcher m = p.matcher(mobiles);
			flag = m.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public static void callPhone(Context context, String tel) {
		if (StringUtil.isEmpty(tel)) {
			tel = "";
		}
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
		context.startActivity(intent);
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static boolean unzip(String srcFile, String dstPath) {

		try {
			File fSourceZip = new File(srcFile);
			ZipFile zipFile = new ZipFile(fSourceZip);
			Enumeration<? extends ZipEntry> e = zipFile.entries();
			boolean skipRoot;
			while (e.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) e.nextElement();
				File destinationFilePath = new File(dstPath, entry.getName());
				// if(skipRoot){
				//
				// }
				destinationFilePath.getParentFile().mkdirs();
				if (entry.isDirectory()) {
					continue;
				} else {
					BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

					int b;
					byte buffer[] = new byte[1024];
					FileOutputStream fos = new FileOutputStream(destinationFilePath);
					BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

					while ((b = bis.read(buffer, 0, 1024)) != -1) {
						bos.write(buffer, 0, b);
					}
					bos.flush();
					bos.close();
					bis.close();
				}
			}
			return true;
		} catch (IOException ioe) {
		}
		return false;
	}

	public static void clearDirectory(File dir) throws IOException {
		File[] files = dir.listFiles();
		if (files == null) {
			throw new IOException("not a readable directory: " + dir);
		}
		for (File file : files) {
			if (file.isDirectory()) {
				clearDirectory(file);
			}
			if (!file.delete()) {
				throw new IOException("failed to delete file: " + file);
			}
		}
	}

	// public static void getVersion(final Context context, final boolean show) {
	// Animation rolAnimation = AnimationUtils.loadAnimation(context, R.anim.rolate);
	// LinearInterpolator lir = new LinearInterpolator();
	// rolAnimation.setInterpolator(lir);
	//
	// final int localVersion = StringUtil.getLoaclVersion(context);
	//
	// String url = HttpUrl.VERSION_PATH;
	//
	// HttpClientAsync client = HttpClientAsync.getInstance();
	// client.get(url + "?type=0&appName=tiangou", null, HttpUrl.CONTENT_TYPE, new HttpCallBack() {
	//
	// @Override
	// public void onHttpSuccess(Object arg0) {
	// try {
	// String result = arg0.toString();
	// if (!StringUtil.isEmpty(result)) {
	// AppInfoEntity entity = (AppInfoEntity) JSON.parseObject(arg0.toString(),
	// AppInfoEntity.class);
	// if (entity.getStatus() == 1) {
	// AppInfoBean bean = entity.getContents();
	// if (null != bean) {
	// if (localVersion >= bean.getVersionCode()) {
	// if (show) {
	// ToastUtil.showMessage(R.string.current_version_last);
	// }
	// } else {
	// builderDialog(bean, context, bean.getUpdateType());
	// }
	//
	// }
	// } else {
	// if (show) {
	// ToastUtil.showMessage(R.string.info_version_sb);
	// }
	// }
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	//
	// @Override
	// public void onHttpStarted() {
	//
	// }
	//
	// @Override
	// public void onHttpFailure(Exception arg0, String arg1) {
	// // isRequest = false;
	// if (show) {
	// if (!TextUtils.isEmpty(arg1)) {
	//
	// ToastUtil.showMessage(arg1);
	//
	// } else if (!SCSDBaseApplication.isNetworkAvailable(context)) {
	// ToastUtil.showMessage(R.string.info_not_net);
	// } else {
	// ToastUtil.showMessage(R.string.getmsg_fail);
	// }
	// }
	// }
	// });
	// }

	// private static void builderDialog(final AppInfoBean bean, final Context context, final int type) {
	// AlertDialog.Builder factory = new AlertDialog.Builder(context);
	// factory.setTitle(context.getResources().getString(R.string.dialog_more_update));
	// factory.setMessage(StringUtil.getDefultString(bean.getDesc()));
	// factory.setIcon(R.drawable.icon);
	// factory.setPositiveButton(context.getResources().getString(R.string.update),
	// new DialogInterface.OnClickListener() {
	//
	// public void onClick(DialogInterface dialog, int which) {
	// Uri mUri = Uri.parse(bean.getUrl());
	// Intent intent = new Intent(Intent.ACTION_VIEW, mUri);
	// context.startActivity(intent);
	// if (type == 1) {
	// StringUtil.onExit(context);
	// }
	// }
	// });
	// factory.setNegativeButton(context.getResources().getString(R.string.cancel),
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog, int which) {
	// if (type == 1) {
	// StringUtil.onExit(context);
	// }
	//
	// }
	// });
	// factory.create().show();
	// }

	/**
	 * make true current connect service is wifi
	 * @param mContext
	 * @return
	 */
	public static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	// public static boolean isTokenUse() {
	// mBaseToken = ShareCookie.getTokenInfo();
	// if (null != mBaseToken) {
	// long o = (mBaseToken.getIssued() + mBaseToken.getExpiresIn() * 1000)
	// - System.currentTimeMillis();
	// if (o > 0) {
	// return true;
	// } else {
	// return false;
	// }
	// }
	// return false;
	// }

	public static void hideSoftInput(Context context) {
		if (context == null) {
			return;
		}
		InputMethodManager manager = ((InputMethodManager) context
				.getSystemService(Activity.INPUT_METHOD_SERVICE));
		View view = ((Activity) context).getCurrentFocus();
		if (view == null) {
			return;
		}
		manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static String idToAddress(int provinceId, int cityId, int countyId) {
		DbHelper dbHelper = new DbHelper(BaBaseApplication.getAppContext());
		String province = "";
		String city = "";
		String county = "";
		if (countyId != 0) {
			try {
				Area areas = dbHelper.getAreaDao().queryForId(countyId);
				if (null != areas) {
					county = areas.getAreaName();
					provinceId = areas.getProvinceId();
					cityId = areas.getCityId();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (provinceId != 0) {
			try {
				Province provinces = dbHelper.getProvinceDao().queryForId(provinceId);
				if (null != provinces) {
					province = provinces.getProvinceName();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (cityId != 0) {
			try {
				City citys = dbHelper.getCityDao().queryForId(cityId);
				if (null != citys) {
					city = citys.getCityName();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return province + city + county;
	}

	public class UploadTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String string = "";
			try {
				File file = new File(params[0]);
				if (file.exists()) {
					string = upLoadTest(HttpUrl.getUrl(HttpUrl.UploadNormalImage), params[0]);
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return string;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!StringUtil.isEmpty(result)) {
				try {
					BaseDataEntity entity = (BaseDataEntity) JSON.parseObject(result,
							BaseDataEntity.class);
					if (entity != null) {
						if (!StringUtil.isEmpty(entity.getData())) {
							ToastUtils.showMessage("修改头像成功");
						} else {
							ToastUtils.showMessage("修改头像失败");
						}
					} else {
						ToastUtils.showMessage("修改头像失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
					ToastUtils.showMessage("修改头像失败");
				}
			} else {
				ToastUtils.showMessage("修改头像失败");
			}
		}

	}

	private String upLoadTest(String url, String filePath) {
		HttpClient httpclient = new DefaultHttpClient();
		String strResult = "";
		HttpPost httppost = new HttpPost(url);
		File file = new File(filePath);
		MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); // 文件传输
		try {
			mBuilder.addBinaryBody("file", new FileInputStream(file),
					ContentType.APPLICATION_OCTET_STREAM, ".jpg");
			// mBuilder.addTextBody("UserId", ShareCookie.getUserId());
			httppost.setEntity(mBuilder.build());
			httppost.setHeader("User-Agent", "Tiangou-Android");
			HttpResponse response = httpclient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			} else {
				return strResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

}
